<?php
/**
 * 支付下单service层
 * */

namespace App\Http\Services;

use App\Http\Model\FinanceDiamond;
use App\Http\Model\FinanceRechargeOrder;
use App\Http\Model\PayException;
use App\Http\Model\UserReverify;
use App\Http\Model\UserVerify;
use App\Lib\LLRequest;
use App\Lib\Pay\Applepay\ApplePayResults;
use App\Lib\xdpay;
use Illuminate\Support\Facades\Log;
use Yansongda\Pay\Pay;
use Illuminate\Support\Facades\Redis;
use App\Lib\Alipay;

use function AlibabaCloud\Client\json;

//支付配置文件定义
const PAY_CONFIG_ALIPAY_APP = "pay_ali_app"; //支付宝APP
const PAY_CONFIG_WX_APP = "pay_wx_app_3"; //微信APP
const PAY_CONFIG_IOS = "pay_ios"; //ios
const PAY_CONFIG_ALIPAY_H5 = "pay_ali_h5"; //支付宝h5
const PAY_CONFIG_WX_H5 = "pay_wx_h5"; //微信h5
const PAY_CONFIG_WX_MP = "pay_wx_h5"; //微信公众号

//一个支付类型对应的日志流水，一个支付配置对应一个流水类型，这里没有特殊需求尽量不要重复，新增配置就递增
const PAY_STREAM_TYPE = [
    PAY_CONFIG_ALIPAY_APP => 1,
    PAY_CONFIG_WX_APP => 2,
    PAY_CONFIG_IOS => 3,
    PAY_CONFIG_ALIPAY_H5 => 6,
    PAY_CONFIG_WX_H5 => 7,
    PAY_CONFIG_WX_MP => 8,
];

//根据pay_type找到对应的config_name，无特殊情况这里不用修改
const PAY_TYPE_MAP = [
    1 => PAY_CONFIG_ALIPAY_APP, //支付宝app
    2 => PAY_CONFIG_WX_APP, //微信app
    3 => PAY_CONFIG_IOS, //苹果
    6 => PAY_CONFIG_ALIPAY_H5, //支付宝h5
    7 => PAY_CONFIG_WX_H5, //微信H5
    8 => PAY_CONFIG_WX_MP, //公众号
];

const CIBN_BASEURL = 'https://openapi.cibn.cc';
const CIBN_MCHNO = '1000150071';
const CIBN_SECRET = 'qk4fb5jckh10hvi1rcniflvzjv7rb1zr';
const CIBN_SALT = 'fgjkl5436sdjg';

class FinancePayServices extends CommonServices
{
    protected $request;
    protected $config;
    protected $body = '钻石充值';
    private $model_finance_diamond;
    private $model_finance_recharge_order;
    protected $xdpayLib;
    private $modelUserVerify;
    private $alipayLib;

    protected $securityKey;
    protected $nowWechatBussinessKey = 'PAY:WECHAT:NOW:USE';//目前微信使用中的商户配置 string PAY:WECHAT:NOW:USE {strign}

    public function __construct(FinanceDiamond $financeDiamond, FinanceRechargeOrder $financeRechargeOrder)
    {
        parent::__construct();
        $this->config = config('pay');
        $this->model_finance_diamond = $financeDiamond;
        $this->model_finance_recharge_order = $financeRechargeOrder;
        $this->xdpayLib = new xdpay();
        $this->modelUserVerify = new UserVerify();
        $this->alipayLib = new Alipay();


    }

    //根据pay_type读取流水id，和支付配置名称
    public function getConfigByPayType($payType)
    {
        $def = [
            1 => PAY_CONFIG_ALIPAY_APP, //支付宝app
            2 => PAY_CONFIG_WX_APP, //微信app
            3 => PAY_CONFIG_IOS, //苹果
            6 => PAY_CONFIG_ALIPAY_H5, //支付宝h5
            7 => PAY_CONFIG_WX_H5, //微信H5
            8 => PAY_CONFIG_WX_MP, //公众号
        ];

        if($payType > 8){
            $result = [
                "config_name" => '', //配置文件名称
                "stream_type" => $payType, //流水类型
            ];
            return $result;
        }

        if (empty($def[$payType])) {
            return [];
        }

        if (empty(PAY_STREAM_TYPE[$def[$payType]])) {
            return [];
        }
        $configName = $def[$payType];
        //获取当前使用中的微信配置
        if($payType == 2){
            $redisWechat = Redis::get($this->nowWechatBussinessKey);
            $configName = empty($redisWechat) ? $def[$payType] : $redisWechat;
        }
        $result = [
            "config_name" => $configName, //配置文件名称
            "stream_type" => PAY_STREAM_TYPE[$def[$payType]], //流水类型
        ];

        return $result;
    }

    /**
     * @desc 微信app预下单
     * @date 2019/1/3
     * */
    public function unifiedOrderWxApp($configName, $order_info)
    {
        $config = $this->config[$configName];
        if (empty($config)) {
            return [];
        }
        $order = [
            'out_trade_no' => $order_info['order_sn'],
            'total_fee' => $order_info['price'],
        ];

        switch ($order_info['recharge_type'] ?? 0) {
            case 0:// 钻石
                $order['body'] = '任何扫码刷单代充都是骗局，您充值的钻石仅用于打赏消费';
                break;
            case 1:// 珍珠
                $order['body'] = '交易订单 - 金豆充值';
                break;
            default:
                break;
        }

        $result = Pay::wechat($config)->app($order);
        return ['wxpay' => json_decode($result->getContent(), true)];
    }

    /**
     * 微信h5支付调转
     * @param $key
     */
    public function referer($key)
    {
        $url = $this->model_finance_recharge_order->getWeixinReferer($key);
        if (empty($url)) {
            return;
        }
        echo '<script> window.location.href = "' . $url . '";</script>';
    }

    /**
     * @desc 微信h5预下单
     * @date 2019/1/3
     * */

    public function unifiedOrderWxH5($configName, $order_info)
    {
        $config = $this->config[$configName];
        if (empty($config)) {
            return false;
        }
        $order = [
            'out_trade_no' => $order_info['order_sn'],
            'total_fee' => $order_info['price'],
        ];

        switch ($order_info['recharge_type'] ?? 0) {
            case 0:// 钻石
                $order['body'] = '任何扫码刷单代充都是骗局，您充值的钻石仅用于打赏消费';
                break;
            case 1:// 珍珠
                $order['body'] = '交易订单 - 金豆充值';
                break;
            default:
                break;
        }

        $result = Pay::wechat($config)->wap($order);
        return ['h5wxpay' => $result->getTargetUrl()];
    }

    /**
     * @desc 支付宝app下单
     * @date 2019/1/3
     * */
    public function unifiedOrderAlipayApp($configName, $order_info, $method = 'app')
    {
        $config = $this->config[$configName];
        if (empty($config)) {
            return [];
        }
        $order = [
            'out_trade_no' => $order_info['order_sn'],
            'total_amount' => floatval($order_info['price']) / 100,
        ];

        switch ($order_info['recharge_type'] ?? 0) {
            case 0:// 钻石
                $order['subject'] = '交易订单 - 钻石充值';
                break;
            case 1:// 珍珠
                $order['subject'] = '交易订单 - 金豆充值';
                break;
            default:
                break;
        }

        // $isWhiteFlag = $this->model_finance_recharge_order->aliPayH5White($order_info['user_id']);
        // if (!$isWhiteFlag) {
        //     $userVerifyData = $this->modelUserVerify->getSuccess($order_info['user_id']);
        //     if (empty($userVerifyData)) {
        //         //判断用户是否首充 （首充允许充值）
        //         $pay_counts = $this->model_finance_recharge_order->getPayNumByUserId($order_info['user_id']);
        //         if ($pay_counts > 0) {
        //             return [];
        //         }
        //     } else {
        //         $order['ext_user_info'] = [
        //             'name' => $userVerifyData['idcard_name'],
        //             'cert_type' => 'IDENTITY_CARD',
        //             'cert_no' => $userVerifyData['idcard_number'],
        //             'need_check_info' => 'T',
        //         ];
        //     }


        // }

        $alipay = Pay::alipay($config)->$method($order);
        return ['alipay' => $alipay->getContent()];
    }

    /**
     * @desc 支付宝app下单
     * @date 2019/1/3
     * */
    public function orderAlipayApp($configName, $order_info, $method = 'app')
    {
        $res = $this->alipayLib->setAlipayConfig(PAY_CONFIG_ALIPAY_APP);
        if (!$res) {
            return [];
        }
        $subject = '交易订单 - 钻石充值';
        $outTradeNo = $order_info['order_sn'];
        $totalAmount = floatval($order_info['price']) / 100;

        $orderStr = $this->alipayLib->payment($subject, $outTradeNo, $totalAmount);

        return ['alipay' => $orderStr];
    }

    /**
     * @desc 支付宝h5下单
     * */

    public function unifiedOrderAlipayH5($configName, $order_info, $method = 'app')
    {
        $config = $this->config[$configName];
        if (empty($config)) {
            return false;
        }
        $order = [
            'out_trade_no' => $order_info['order_sn'],
            'total_amount' => floatval($order_info['price']) / 100,
        ];

        switch ($order_info['recharge_type'] ?? 0) {
            case 0:// 钻石
                $order['subject'] = '交易订单 - 钻石充值';
                break;
            case 1:// 珍珠
                $order['subject'] = '交易订单 - 金豆充值';
                break;
            default:
                break;
        }

        $isWhiteFlag = $this->model_finance_recharge_order->aliPayH5White($order_info['user_id']);
        if (!$isWhiteFlag) {
            $userVerifyData = $this->modelUserVerify->getSuccess($order_info['user_id']);
            if (empty($userVerifyData)) {
                //判断用户是否首充 （首充允许充值）
                $pay_counts = $this->model_finance_recharge_order->getPayNumByUserId($order_info['user_id']);
                if ($pay_counts > 0) {
                    return [];
                }
            } else {
                $order['ext_user_info'] = [
                    'name' => $userVerifyData['idcard_name'],
                    'cert_type' => 'IDENTITY_CARD',
                    'cert_no' => $userVerifyData['idcard_number'],
                    'need_check_info' => 'T',
                ];
            }
        }

        $alipay = Pay::alipay($config)->$method($order);
        return ['alipay' => $alipay->getContent()];

    }

    /**
     * @desc 支付宝h5下单
     * */
    public function orderAlipayH5($configName, $order_info, $method = 'app')
    {
        $res = $this->alipayLib->setAlipayConfig(PAY_CONFIG_ALIPAY_APP);
        if (!$res) {
            return [];
        }
        $subject = '交易订单 - 钻石充值';
        $outTradeNo = $order_info['order_sn'];
        $totalAmount = floatval($order_info['price']) / 100;

        $orderStr = $this->alipayLib->paymentH5($subject, $outTradeNo, $totalAmount);

        return ['alipay' => $orderStr];
    }

    //获取用户openID
    public function getUserOpenId($configName,$code){
        $config = $this->config[$configName];
        if (empty($config)) {
            return false;
        }
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $params = [
            'appid' => $config['app_id'],
            'secret' => $config['app_secret'],
            'code' => $code,
            'grant_type' => 'authorization_code'
        ];

        $token = curl_request($get_token_url, $params, "urlencoded", "GET");
        if(!empty($token)){
            $token = json_decode($token,true);
        }
        
        return $token;
    }
    
    /**
     * 微信公众号下单
     * @param $order_info
     * @return mixed
     */
    public function unifiedOrderWxMp($configName, $order_info,$openid)
    {
        $config = $this->config[$configName];
        if (empty($config)) {
            return false;
        }

        
        $order = [
            'out_trade_no' => $order_info['order_sn'],
            'total_fee' => $order_info['price'],
            'openid' => $openid
        ];

        switch ($order_info['recharge_type'] ?? 0) {
            case 0:// 钻石
                $order['body'] = '交易订单 - 钻石充值';
                break;
            case 1:// 珍珠
                $order['body'] = '交易订单 - 金豆充值';
                break;
            default:
                break;
        }

        $result = Pay::wechat($config)->mp($order);

        return ['wxpay' => $result->toArray()];
    }

    /**
     * @desc 苹果内购下单
     * @date 2019/1/4
     * */
    public function unifiedOrderApple($order_info)
    {
        return $order_info;
    }


    /**
     * 支付宝通知验证
     * @return null|\Yansongda\Supports\Collection
     */
    public function alipay_notify_verify()
    {
        $alipay = Pay::alipay($this->config[PAY_TYPE_MAP[1]]);
        try {
            $data = $alipay->verify();
            return $data->toArray();
            //Log::debug('Alipay notify', $data->all());
        } catch (\Exception $e) {
            //echo $e->getMessage();
            return null;
        }
    }

    /**
     * 支付宝通知验证
     */
    public function alipayNotifyVerify($parameters)
    {
        $res = $this->alipayLib->setAlipayConfig(PAY_CONFIG_ALIPAY_APP);
        $res = $this->alipayLib->verifyNotify($parameters);
        return $res;
    }

    /**
     * 支付宝通知验证
     * @return null|\Yansongda\Supports\Collection
     */
    public function alipay_h5_notify_verify()
    {
        $alipay = Pay::alipay($this->config[PAY_TYPE_MAP[6]]);
        try {
            $data = $alipay->verify();
            return $data->toArray();
            //Log::debug('Alipay notify', $data->all());
        } catch (\Exception $e) {
            //echo $e->getMessage();
            return null;
        }
        return null;
    }

    /**
     * 支付宝通知验证H5
     */
    public function alipayH5NotifyVerify($parameters)
    {
        $res = $this->alipayLib->setAlipayConfig(PAY_CONFIG_ALIPAY_H5);
        $res = $this->alipayLib->verifyNotify($parameters);
        return $res;
    }

    /**
     * 微信公众号通知验证
     * @return null|\Yansongda\Supports\Collection
     */
    public function wxmppay_notify_verify()
    {
        $pay = Pay::wechat($this->config[PAY_TYPE_MAP[8]]);
        try {
            $data = $pay->verify();
            return $data->toArray();
            //Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            //echo  $e->getMessage();
            return null;
        }
    }

    /**
     * 微信通知验证
     * @return array|null
     */
    public function wxpay_notify_verify()
    {
        $pay = Pay::wechat($this->config[PAY_TYPE_MAP[2]]);
        try {
            $data = $pay->verify();
            return $data->toArray();
            //Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            //echo  $e->getMessage();
            return null;
        }
        return null;
    }


    public function apple_notify_order($receipt_data)
    {
        $curr_user = $this->user->get_current_user();
        if (empty($curr_user)) {
            return null;
        }
        $count = $this->model_finance_recharge_order->hasAppleReceiptInc($curr_user['user_id'], $receipt_data);
        if ($count > 1) {
            write_log("applePay", "apple_notify_verify-02", $receipt_data);
            return null;
        }
        $apple_orders = ApplePayResults::get_order_info($receipt_data);
        write_log("applePay", "apple_orders", $apple_orders);

        $ret_data = [];
        foreach ($apple_orders as $order) {
            if ($order['bundle_id'] != 'com.ningjing.dada') {
                continue;
            }

            // TODO 判断钻石 与 珍珠规格 交替使用
            $rule = $this->model_finance_diamond->getDiamondRulePi($order['product_id']);
            if (empty($rule)) {
                continue;
            }

            $count = $this->model_finance_recharge_order->hasAppleTransactionIdInc($order['transaction_id']);
            if ($count > 1) {
                continue;
            }
            $order['out_order_sn'] = $order['transaction_id'] . $order['purchase_date_ms'];
            $old_order = $this->model_finance_recharge_order->getOrderByOutsn($order['out_order_sn']);
            if (!empty($old_order)) {
                continue;
            }
            $order['user_id'] = $curr_user['user_id'];
            $order['rule_id'] = $rule['rule_id'];
            $order['channel_id'] = $curr_user['channel_id'];

            // TODO 增加规则充值类型 存在钻石数量则是 0=钻石充值，否则是 1=珍珠充值
            $order['rule_recharge_type'] = isset($rule['diamond_amount']) ? 0 : 1;

            $ret_data [] = $order;
        }
        return $ret_data;
    }

    //判断用户是否需要再次认证
    public static function needReverify($userId)
    {
        $exceptionCount = (new PayException())->getExceptionCountByUserId($userId);
        if ($exceptionCount <= 0) {
            return false;
        }

        //判断是否已经二次认证了
        $userReverify = (new UserReverify())->getLatest($userId);
        $ua = LLRequest::parse_app_UA();
        //如果已经二次认证过了
        if (!empty($userReverify)) {
            if ($ua['guid'] == $userReverify['guid']) {
                return false;
            }
        }
        return true;
    }

    //判断用户是否需要再次认证 h5用 这个不判断设备号
    public static function needReverifyH5($userId)
    {
        $exceptionCount = (new PayException())->getExceptionCountByUserId($userId);
        if ($exceptionCount <= 0) {
            return false;
        }

        //判断是否已经二次认证了
        $userReverify = (new UserReverify())->getLatest($userId);
        //如果已经二次认证过了
        if (!empty($userReverify)) {
            return false;
        }
        return true;
    }

    //支付宝单日单人充值最大金额限制
    public static function getTodayRechargeTotalByPayTypeAndUserId($userId, $payTypes)
    {
        return (new FinanceRechargeOrder())->getTodayRechargeTotalByPayTypeAndUserId($userId, $payTypes);
    }

    //三方微信支付
    public function unifiedThreeWechat($order_info){
        $orderSn =  $order_info['order_sn'];
        $total = $order_info['price'];
        $userId = $order_info['user_id'];

        $payParams = [
            'order_type' => 'get_order',//固定参数
            'order_id' => $orderSn,//订单20位数字
            'order_amount' => $total/100,//单位元
            'pay_type' => 'wxPay',
            'user_id' => $userId,
            'notify' => env('APP_URL').'/finance/pay/threewx_notify',
        ];
        //加签
        $payParams['sign'] = $this->threeSignParam($payParams);
        //调用支付
        $url = 'http://hyzf.xiaochaipaidui.com/get_order';

        $res = curl_request($url, $payParams, 'urlencoded', 'POST');
        $res = json_decode($res,true);
        write_log("pay_three", "INFO wx", $res);
        if(!empty($res) && $res['status'] == 200){
            //微信特殊处理若返回https开头则替换成weixin://dl/business/?t=
            $payUrl = $res['url'];
            $strArr = parse_url($payUrl);
            
            if(isset($strArr['scheme']) && $strArr['scheme'] === 'https'){
                $wechatId = $strArr['path'];
                $wechatId = ltrim($wechatId,'/');
                $payUrl = 'weixin://dl/business/?t='.$wechatId;
            }
            return ['url'=>$payUrl];
        }else{
            return [];
        }
    }

    //三方支付宝
    public function unifiedThreeAliPay($order_info){
        $orderSn =  $order_info['order_sn'];
        $total = $order_info['price'];
        $userId = $order_info['user_id'];

        $payParams = [
            'order_type' => 'get_order',//固定参数
            'order_id' => $orderSn,//订单20位数字
            'order_amount' => $total/100,//单位元
            'pay_type' => 'aliPay',
            'user_id' => $userId,
            'notify' => env('APP_URL').'/finance/pay/threeali_notify',
        ];
        //加签
        $payParams['sign'] = $this->threeSignParam($payParams);
        //调用支付
        $url = 'http://hyzf.xiaochaipaidui.com/get_order';

        $res = curl_request($url, $payParams, 'urlencoded', 'POST');
        $res = json_decode($res,true);
        write_log("pay_three", "INFO ali", $res);
        if(!empty($res) && $res['status'] == 200){
            return ['url'=>$res['url']];
        }else{
            return [];
        }
    }

    //三方微信回调
    public function three_notify_check($notify){
        if($notify['returncode'] != 00){
            return false;
        }
        return true;
    }

    //三方签名规则
    public function threeSignParam($param=[]){
        if(empty($param)){
            return '';
        }
        // 对数组的值进行降序排序
        $firstArr = $param;
        krsort($firstArr);
        $str = http_build_query($firstArr);
        $str = urldecode($str);
        $md5Str6 = substr(md5($str), 8, 16); //转md5 16位
        $strtolowerStr = strtolower($md5Str6);//转为小写
        //对数据升序排序
        $secondArr = $param;
        ksort($secondArr);
        $secondArr['key'] = $strtolowerStr;
        
        $upStr = http_build_query($secondArr);
        $upStr = urldecode($upStr);
        $finalStr = md5($upStr);
        $finalStr = strtoupper($finalStr);
        return $finalStr;
    }

    //cibn支付宝
    public function unifiedCibnAliPay($order_info){
        $orderSn =  $order_info['order_sn'];
        $total = $order_info['price'];

        $microtime = microtime(true);
        $millis = round($microtime * 1000);

        $payParams = [
            'version' => '1.0.0',//固定参数
            'signType' => 'MD5',//固定参数
            'mchNo' => CIBN_MCHNO,// 商户号
            'reqTime' => $millis,// 请求毫秒数
            'mchOrderNo' => $orderSn,//
            'productCode' => 'ALI_APP',//
            'amount' => bcdiv($total, 100, 2),//单位元
            'currency' => 'cny',
            'clientIp' => $this->getRealIp(),
            'subject' => '充值支付',
            'body' => md5($orderSn . CIBN_SALT),
            'notifyUrl' => env('APP_URL').'/finance/pay/cibnali_notify',
            'expiredTime' => '3600',
            'payChannel' => '1',
        ];
        //加签
        $payParams['sign'] = $this->cibnSign($payParams);
        //调用支付
        $url = CIBN_BASEURL . '/api/v2/pay/order-create';

        $res = curl_request($url, $payParams, 'json', 'POST');
        $res = json_decode($res,true);
        write_log("pay_cibn", "order-create", $res);
        if(!empty($res) && $res['code'] == 200){
            return ['alipay'=>$res['data']['payData']];
        }else{
            return [];
        }
    }

    public function getRealIp()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    public function cibnSign($data)
    {
        if (empty($data)) {
            return '';
        }
        ksort($data);//降序
        $queryString = '';
        foreach ($data as $key => $value) {
            $queryString .= $key . '=' . $value . '&';
        }
        // 去除最后一个"&"字符
        $queryString = rtrim($queryString, '&') . CIBN_SECRET;
        $sign = strtoupper(md5($queryString));

        return $sign;
    }

    //cibn支付回调
    public function cibn_notify_check($notify){
//        $notify = '{"body":"35da91c7eb4c145cb5380ca73bf8ce59","buyerAccount":"133****3749","buyerInfo":"2088122709397831","mchNo":"1000150071","merchantTradeNo":"2410081150012024100888374","payTime":1728402614000,"platformOutTradeNo":"OP24100823501843680256956035073","productCode":"ALI_APP","reqTime":"1728402615212","sign":"ae285203f5d73681c689da2624bc06e7","state":2,"totalAmount":198,"tradeNo":"2024100822001497831449046182"}';
//        $notify = json_decode($notify, true);

        if ($notify['state'] != 2) {
            return false;
        }

        if ($notify['body'] != md5($notify['merchantTradeNo'] . CIBN_SALT)) {
            return false;
        }

        $order_query = $this->cibn_query($notify['merchantTradeNo']);
        if (empty($order_query)) {
            return false;
        }

        if ($order_query['state'] != 2) {
            return false;
        }

        return true;
    }

    public function cibn_query($mchNo) {
        $microtime = microtime(true);
        $millis = round($microtime * 1000);

        $payParams = [
            'version' => '1.0.0',//固定参数
            'signType' => 'MD5',//固定参数
            'mchNo' => CIBN_MCHNO,// 商户号
            'reqTime' => $millis,// 请求毫秒数
            'merchantTradeNo' => $mchNo,
        ];
        //加签
        $payParams['sign'] = $this->cibnSign($payParams);
        //调用支付
        $url = CIBN_BASEURL . '/api/v2/pay/order-query';

        $res = curl_request($url, $payParams, 'json', 'POST');
        $res = json_decode($res,true);
        write_log("pay_cibn", "order-query", $res);
        if(!empty($res) && $res['code'] == 200){
            return $res['data'];
        }else{
            return [];
        }
    }


    //微保支付
    public function unifiedweibaoAliPay($order_info,$paystoreid,$paystoreaes,$paystoremd5){
        $orderSn =  $order_info['order_sn'];
        $total = $order_info['price'];
        $payParams = [
            'externalId' => $paystoreid,// 商户号
            'merchantTradeNo' => $orderSn,//订单号
            'totalAmount' => bcdiv($total, 100, 2),//单位元
            'merchantSubject' => $orderSn.'订单', //订单标题
            'externalGoodsType' => '1', //订单标题
            'clientIp' => $this->getRealIp(),
            'merchantPayNotifyUrl' => '',//商户异步通知URL
            'riskControlNotifyUrl' => env('APP_URL').'/finance/pay/weibaoali_notify',//风控通知URL
            'typeIndex' => '3',
            'payChannel' => '1',
        ];
        $md5Key = $paystoremd5;
        $timestamps = time();
        $plainText = md5($md5Key. ":" .$timestamps);
        $visitAuth=$this->encrypt($plainText,$paystoreaes);
//        $visitAuth2=$this->decrypt($visitAuth,$paystoreaes);
        $httpHeader=[
            "Accept:application/json;",
            "charset:utf-8;",
            "timeStamp:".$timestamps,
            "visitAuth:".$visitAuth,
        ];
        //调用支付
//        $url = CIBN_BASEURL . 'apiv2/payment/pay';
        $url =' https://pay.weibaozhifu.com/apiv2/payment/pay';
//        $res = curl_request($url, $payParams, 'json', 'POST',$httpHeader);
        $res =$this->posturl($url, $payParams, $httpHeader);

        $res = json_decode($res,true);
        write_log("pay_weibao", "order-create", $res);

        if(!empty($res) && $res['code'] == 200){
            return ['alipay'=>$res['data']['payData']];
        }else{
            return [];
        }
    }

    //微保支付回调
    public function weibao_notify_check($notify){
//        $notify = '{"body":"35da91c7eb4c145cb5380ca73bf8ce59","buyerAccount":"133****3749","buyerInfo":"2088122709397831","mchNo":"1000150071","merchantTradeNo":"2410081150012024100888374","payTime":1728402614000,"platformOutTradeNo":"OP24100823501843680256956035073","productCode":"ALI_APP","reqTime":"1728402615212","sign":"ae285203f5d73681c689da2624bc06e7","state":2,"totalAmount":198,"tradeNo":"2024100822001497831449046182"}';
//        $notify = json_decode($notify, true);

        if ($notify['state'] != 2) {
            return false;
        }

        if ($notify['body'] != md5($notify['merchantTradeNo'] . CIBN_SALT)) {
            return false;
        }

        $order_query = $this->cibn_query($notify['merchantTradeNo']);
        if (empty($order_query)) {
            return false;
        }

        if ($order_query['state'] != 2) {
            return false;
        }

        return true;
    }

//    public function weibaoSign($data)
//    {
//
//        if (empty($data)) {
//            return '';
//        }
//        ksort($data);//降序
//        $queryString = '';
//        foreach ($data as $key => $value) {
//            $queryString .= $key . '=' . $value . '&';
//        }
////        $md5Key = $queryString;
//        $md5Key = "Q6A2L2QIsD+";
//        $timestamps = time();
//        $plainText = md5($md5Key. ":" .$timestamps);
//        $sign = $this->encrypt($plainText);
//
//        // 去除最后一个"&"字符
////        $queryString = rtrim($queryString, '&') . CIBN_SECRET;
////        $sign = strtoupper(md5($queryString));
//        return $sign;
//    }
    /**
     * 加密
     * @param string $plainText 明文
     * @return bool|string
     */
    public function encrypt($plainText,$paystoreaes)
    {
        $aesKey =$paystoreaes;
        $iv = substr($aesKey,0,16);
        $originData = (openssl_encrypt($this->addPkcs7Padding($plainText, 16), 'AES-128-CBC', $this->securityKey, OPENSSL_NO_PADDING, $iv));

        return $originData === false ? false : base64_encode($originData);
    }

    /**
     * 解密
     * @param string $cipherText 密文
     * @return bool|string
     */
    public function decrypt($cipherText,$paystoreaes)
    {
        $aesKey = $paystoreaes;
        $iv = substr($aesKey,0,16);
        $str = base64_decode($cipherText);
        $data = openssl_decrypt($str, 'AES-128-CBC', $this->securityKey, OPENSSL_NO_PADDING, $iv);
        return $data === false ? false : $this->stripPKSC7Padding($data);
    }
    /**
     * 填充算法
     * @param string $source
     * @return string
     */
    private function addPKCS7Padding($source)
    {
        $source = trim($source);
        $block = 16;

        $pad = $block - (strlen($source) % $block);

        if ($pad <= $block) {
            $char = chr($pad);
            $source .= str_repeat($char, $pad);
        }
        return $source;
    }
    /**
     * 移去填充算法
     * @param string $source
     * @return string
     */
    private function stripPKSC7Padding($source)
    {
        $char = substr($source, -1);
        $num = ord($char);
        if ($num === 62) return $source;
        $source = substr($source, 0, -$num);
        return $source;
    }
   public function posturl($url,$data,$headerArray){
        // $data  = json_encode($data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
//        var_dump($output);
       if (false === $output) {
           $ret = curl_errno($curl);
           var_dump($ret);
       }

        curl_close($curl);
        return json_decode($output,true);
    }
}